package com.luffyzhao.demo.scheduled;

import com.luffyzhao.demo.properties.ApplicationProperties;
import com.luffyzhao.demo.utils.FileUtil;
import com.surftools.BeanstalkClient.Client;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collection;

@Service
public class JobProduct {
    private static Logger logger;
    private ApplicationProperties properties;

    @Autowired
    private Client client;

    public JobProduct(ApplicationProperties properties) {
        this.properties = properties;
    }

    @Scheduled(fixedRateString = "${client.rate}", initialDelay = 1000L)
    public void process() {
        final Collection<File> fileList = FileUtil.getFileList(
                this.properties.getReceiptDir()
        );
        if (CollectionUtils.isEmpty((Collection) fileList)) {
            logger.debug("没有需要处理的回执，结束本次任务。");
            return;
        }

        for (final File file : fileList) {
            try {
                if (file.exists()) {
                    final String msg = FileUtils.readFileToString(file, StandardCharsets.UTF_8);

                    client.useTube(properties.getProducerTube());
                    client.put(1, 1, 5000, msg.getBytes());

                    logger.info("回执处理完毕: " + msg);

                    FileUtil.moveToTargetDir(file, this.properties.getReceiptBackDir());
                }
            } catch (Exception ex) {
                logger.error(file.getName() + ex.getMessage());
                try {
                    FileUtil.moveToTargetDir(file, this.properties.getErrorDir());
                } catch (IOException e) {
                    logger.error("失败目录不能写入：" + this.properties.getErrorDir());
                }
            }
        }

    }

    static {
        JobProduct.logger = LoggerFactory.getLogger((Class) JobProduct.class);
    }
}
